<?php
declare(strict_types=1);

namespace Zyucv7\Core\Database;
use Zyucv7\Core\Database\Driver AS DatabaseDriver;
use Zyucv7\Core\Database\DatabaseException;

class Manager
{
    protected static $instances = [];

    /**
     * 获取数据库驱动实例
     * @param array $config 数据库配置数组, 例如 ['type' => 'mysql', 'host' => 'localhost', 'user' =>
     * 'root', 'password' => '', 'database' => 'test', 'prefix' => '']
     * @return DatabaseDriver 返回对应的数据库驱动实例
     * @throws \Exception 如果配置无效或驱动不存在则抛出异常
     */
    public static function connect(array $config): DatabaseDriver
    {
        if(!$config) {
            throw DatabaseException::InvalidArgument('Database Manager config not found.');
        }
        $key = md5(serialize($config));
        if (!isset(self::$instances[$key])) {
            $type = strtolower($config['type'] ?? 'mysql');
            $className = '\\Zyucv7\\Core\\Database\\Driver\\' . ucfirst($type);
            if (!class_exists($className)) {
                throw new \Exception("Database driver '$type' not found.");
            }
            $instance = new $className($config);
            if (!$instance instanceof Driver) {
                throw new \Exception("Database driver '$type' must extend the Driver class.");
            }
            self::$instances[$key] = $instance;
        }
        return self::$instances[$key];
    }

}